"""
   爬取网易云榜单音乐
   所有热歌榜音乐

"""
import os.path
import time

import requests
import tqdm

headers = {
    # "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    # "Accept-Encoding": "gzip, deflate, br",
    # "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
    "Cookie": "NMTID=00O_Q3QSwAbGTDP60tRh1gCWwts1w0AAAGJ469OAQ; _iuqxldmzr_=32; _ntes_nnid=d80ba0778e61b3b56ff2b4671b0d0b61,1691742082146; _ntes_nuid=d80ba0778e61b3b56ff2b4671b0d0b61; WEVNSM=1.0.0; WNMCID=bxcmhv.1691742082788.01.0; WM_TID=VJCleHKG9c9AERFVFEaBw6hPnep4MLCh; ntes_utid=tid._.17mFgUUpoTRFV0AAFUbF0%252BhaiK94jRwv._.0; sDeviceId=YD-%2FRh0H002bxdBFgFUEBaVx8NS0X1dQ7oC; JSESSIONID-WYYY=qqlg7pXA3hXErU%5Cu3eK6XGJccB1NX48FN1icTTu921Osy1JWmy%2For8JbPk%2FYW6zTQlOB2DUAZPezpHsrA1PZCEsZlN0O4nS93B1HZodCWztjFR1vP7bUijW2QD088OUSjMneJznBQKS3NXbeD23AadvkxvFrdCEbMNxWCHn4X4QbJGO8%3A1692939671243; WM_NI=WkfPBI5AFX2IGS95deQOsUXbc6JMHGPo7GZwhs5KTgiGj0eqoz1sWLNKqdZW41XbcxGEKXaX8vJ8Ar%2BCZoWfapexsinsbFmr2NrV1QHWiHOo1XlPMLMWXOycdRiXVGz2bDE%3D; WM_NIKE=9ca17ae2e6ffcda170e2e6eeaec540fc90b9d4cf3f8c8a8bb6c15a938e9f86d46397b387d8fc45aeef8792eb2af0fea7c3b92a95b5aab1c143f79f8ab9b143858df7d6e76f9391bdb6db6aa1ea86aecb4d94b1f9a8d97dacadfbacd76dab99a6d1e87bada6ff94d6488e95bf85d95df8ef9883e274859b85b9e454fcaa86d9c47ae99d9690d66ea3b0ab99f263aeadaea7f07af292beb7b45b8c89a7a9ce65f388a4b1d0488f8998b0fc69a88ea7b9d54dbaeeaea5c837e2a3; playerid=89441676",
    "User-Agent": "Mozilla/5.0 (X11; Linux aarch64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.188 Safari/537.36 CrKey/1.54.250320 Edg/116.0.0.0",

}


def spider_music():
    url = "https://music.163.com/discover/toplist?id=3779629"

    res = requests.get(url, headers=headers)
    print(res.status_code)
    res.encoding = 'utf-8'
    # print(res.text)

    from bs4 import BeautifulSoup

    soup = BeautifulSoup(res.text, 'html.parser')

    ul_list = soup.find(name='ul', class_='f-hide')
    li_list = ul_list.find_all(name='li')
    song_links = {'song_id': [], 'song_name': []}
    with tqdm.tqdm(total=len(li_list), unit="KB") as pbar:
        for li_tag in li_list:
            a_tag = li_tag.find("a")
            song_id = a_tag["href"].replace("/song?id=", "")
            song_name = a_tag.text
            song_links['song_id'].append(song_id)
            song_links['song_name'].append(song_name)
            pbar.set_description(f"获取网易云数据")
            pbar.update(1)
        return song_links


def download_music(id, name):
    # 下载的接口，传音乐的id进去
    try:
        url = f"http://music.163.com/song/media/outer/url?id={id}.mp3"
        res_music = requests.get(url=url, headers=headers)
        if res_music.status_code != 200:
            print(res_music.text)
        # 将相应的内容转换为二进制格式，通过content，就想图片下载一样，也是通过二进制形式
        music_content = res_music.content
        if not os.path.exists('music'):
            os.mkdir('music')
        with open(f"music\\{name}.mp3", mode='wb') as f:
            f.write(music_content)
    except:
        print(name)


def save_excel(data):
    import pandas as pd
    df = pd.DataFrame(data)
    df.to_excel('Excel/music.xlsx')


def read_excel():
    import pandas as pd
    return pd.read_excel('Excel/music.xlsx')


if __name__ == "__main__":
    save_excel(spider_music())
    data = read_excel()
    # 进度条
    with tqdm.tqdm(total=len(data), unit='kb') as td:
        for index, row in data.iterrows():
            download_music(row['song_id'], row['song_name'])
            td.set_description(f"下载第{index}首")
            td.update(1)
